package cn.ctyun.ipush.dao;

import cn.ctyun.ipush.model.ScheduleJob;
import cn.ctyun.ipush.model.TaskDetailModel;
import cn.ctyun.ipush.model.TaskModel;
import cn.ctyun.ipush.utils.ConfigUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.utils.ScheduleUtils;
import cn.ctyun.ipush.vo.ScheduleJobVo;
import cn.ctyun.ipush.vo.TaskVo;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import org.apache.commons.lang.StringUtils;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-6-16
 * Time: 下午12:42
 * To change this template use File | Settings | File Templates.
 */
@Component
public class ScheduleJobDao {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(ScheduleJobDao.class);


    @Autowired
    private JdbcDao jdbcDao;

    /**
     * 调度工厂Bean
     */
    @Autowired
    private Scheduler scheduler;

    public void saveScheduleJobFromTaskDetailModel(TaskDetailModel taskDetailModel, String taskId) {
        String cronExpression = taskDetailModel.getCronExpression();
        String jobName = taskDetailModel.getTaskName();
        String jobGroupName = taskDetailModel.getTaskGroupName();
        String scheduleJobId = UUIDUtils.getUUID32();
        String isSync = "0";
        String isAutoRun = taskDetailModel.getIsAutoRun();
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setIsDeleted("0");
        scheduleJob.setJobGroup(jobGroupName);
        scheduleJob.setJobName(jobName);
        scheduleJob.setAliasName(taskDetailModel.getTaskAliasName());
        scheduleJob.setScheduleJobId(scheduleJobId);
        scheduleJob.setIsAutoRun(isAutoRun);
        scheduleJob.setGmtCreate(DateUtils.dateToString(new Date()));
        scheduleJob.setIsSync(isSync);
        scheduleJob.setTaskId(taskId);
        scheduleJob.setStatus("0");
        scheduleJob.setGmtCreate(DateUtils.dateToString(new Date()));

        for (String cron : cronExpression.split("@")) {
            scheduleJob.setCronExpression(cron);
            scheduleJob.setJobTrigger(ScheduleUtils.trigerNameFormat(jobName, cron));
            jdbcDao.save(scheduleJob);
        }
    }

    public void setAllJobIsDeleted() {
        try {
            String belongType= ConfigUtils.getStringValue("startTaskBelongType");
            TaskModel taskModle=new TaskModel();
            taskModle.setTaskType(belongType);
            taskModle.setIsDeleted("0");
            List<TaskModel> taskModelList=jdbcDao.queryList(taskModle);
            for(TaskModel taskModel1:taskModelList){
                Criteria criteria = Criteria.update(ScheduleJob.class).set("isDeleted", "1").where("isDeleted", "=", new Object[]{"0"}).where(" and taskId ","=",new Object[]{taskModel1.getTaskModelId()});
                int count = jdbcDao.update(criteria);
            }
            LOG.info("-----------init scheduleJob: success update all job to isDeleted ");
        } catch (Exception ex) {
            LOG.info("-----------init scheduleJob: fail updated all job to isDeleted ");
        }
    }

    /**
     * @param taskVo
     * @return
     */
    public boolean insert(TaskVo taskVo) {
        try {
            ScheduleJobVo scheduleJobVo = ScheduleUtils.createScheduleJobFromTaskVo(taskVo);
            //批量保存ScheduleJob 针对多个cron
            saveScheduleJobFromTaskDetailModel(taskVo.getTaskDetail(), taskVo.getTaskModelId());
            //保存到运行中job
            ScheduleUtils.createScheduleJob(scheduler, taskVo, scheduleJobVo);
            return true;
        } catch (Exception ex) {
            throw new RuntimeException("save scheduleJob fail");
        }
    }

    public int update(ScheduleJob scheduleJob) {
        if (StringUtils.isEmpty(scheduleJob.getScheduleJobId()))
            return 0;
        return jdbcDao.update(scheduleJob);
    }

    public ScheduleJob querySingleResult(ScheduleJob scheduleJob) {
        return jdbcDao.querySingleResult(scheduleJob);
    }

    public ScheduleJob querySingleResult(String scheduleJobId) {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setScheduleJobId(scheduleJobId);
        return querySingleResult(scheduleJob);
    }

    /**
     * @param taskId
     */
    public List<ScheduleJob> getScheduleJobList(String taskId) {
        Criteria criteria = Criteria.select(ScheduleJob.class).where("taskId", new Object[]{taskId});
        List<ScheduleJob> scheduleJobList = jdbcDao.queryList(criteria);
        return scheduleJobList;
    }

    public void setAllJobByTaskId(String taskId) {
        Criteria criteria = Criteria.update(ScheduleJob.class).where("taskId", new Object[]{taskId}).set("isDeleted", "1");
        jdbcDao.update(criteria);
    }

    public void setAllJobIsDeletedByTaskId(String taskId) {
        Criteria criteria = Criteria.update(ScheduleJob.class).where("taskId", new Object[]{taskId}).set("isDeleted", "1");
        jdbcDao.update(criteria);
    }


    public void pauseTask(ScheduleJob scheduleJob, String taskId) {
        String status=scheduleJob.getStatus();
        Criteria criteria = Criteria.update(ScheduleJob.class).where("taskId", new Object[]{taskId}).where("and isDeleted",new Object[]{"0"}).set("status", status);
        jdbcDao.update(criteria);
    }

    public void resumeTask(ScheduleJob scheduleJob, String taskId) {
        String status=scheduleJob.getStatus();
        Criteria criteria = Criteria.update(ScheduleJob.class).where("taskId", new Object[]{taskId}).where("and isDeleted",new Object[]{"0"}).set("status", status);
        jdbcDao.update(criteria);
    }
}
